package com.test.cordova.lifecycle;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.util.Log;

import com.test.cordova.citylist.bean.City;
import com.test.cordova.citylist.common.PinyinComparator;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *  ViewModel  -  LiveData
 */

public class MainViewModel extends ViewModel implements MainView {

    private static final String TAG = MainViewModel.class.getSimpleName();
    private MutableLiveData<List<String>> titles;
    private MutableLiveData<List<User>> users;
    private MutableLiveData<List<City>> cities ;
    private MutableLiveData<List<String>> hotcitys;

    @Override
    public MutableLiveData<List<String>> getTitle() {
        if (titles == null) {
            titles = new MutableLiveData<List<String>>();
        }
        requestTitle();
        return titles;
    }

    private void requestTitle() {
        List<String> data = new ArrayList<>();
        data.add("主题1");
        data.add("主题2");
        data.add("主题3");
        // 子线程  users.postValue(data);
        // 主线程  users.setValue(data);
        titles.setValue(data);
    }

    @Override
    public MutableLiveData<List<User>> getUser() {
        if (users == null) {
            users = new MutableLiveData<List<User>>();
        }
        requestUser();
        return users;
    }

    @Override
    public MutableLiveData<List<City>> getCitys() {
        if (cities == null) {
            cities = new MutableLiveData<>();
        }
        List<City> data = new ArrayList<>();
        data.add(new City("安康"));
        data.add(new City("安庆"));
        data.add(new City("安阳"));
        data.add(new City("北京"));
        data.add(new City("白城"));
        data.add(new City("长安"));
        data.add(new City("潮州"));
        Collections.sort(data,new PinyinComparator());
        cities.setValue(data);
        Log.e(TAG,Thread.currentThread().getName());
        return cities;
    }

    @Override
    public MutableLiveData<List<String>> getHotcitys() {
        if (hotcitys == null) {
            hotcitys = new MutableLiveData<>();
        }
        List<String> data = new ArrayList<>();
        String name[]={"北京","上海","广州","杭州","深圳","成都"};
        for (int i = 0; i <name.length; i++) {
            data.add(name[i]);
        }
        hotcitys.setValue(data);

        return hotcitys;
    }

    /**
     * 执行异步任务请求数据
     */
    private void requestUser() {
        List<User> data = new ArrayList<>();
        data.add(new User("du",19));
        data.add(new User("ning",19));
        data.add(new User("wei",19));
        // 子线程  users.postValue(data);
        // 主线程  users.setValue(data);
        users.setValue(data);
    }


}
